package com.xtgg.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.media.ThumbnailUtils;
import android.os.Environment;

@SuppressLint("SimpleDateFormat")
public class Utils {
	public static final String PACKAGE_NAME = "com.hunantv.imgo.guizhou";// package
																			// name

	public static String getClientVersionHead(Context context) {

		String pName = "com.hunantv.imgo.activity";
		String versionName = getVersionName(context);
		return "Android|" + versionName;
	}

	public static String getVersionName(Context context) {
		String versionName = "1.0";
		try {
			PackageInfo pinfo = context.getPackageManager().getPackageInfo(
					PACKAGE_NAME, PackageManager.GET_CONFIGURATIONS);
			versionName = pinfo.versionName;
		} catch (NameNotFoundException e) {

		}

		return versionName;
	}

	public static int getVersionCode(Context context) {

		int versionCode = 8;
		try {
			PackageInfo pinfo = context.getPackageManager().getPackageInfo(
					PACKAGE_NAME, PackageManager.GET_CONFIGURATIONS);
			versionCode = pinfo.versionCode;
		} catch (NameNotFoundException e) {

		}

		return versionCode;
	}

	public static int readPictureDegree(String path) {
		int degree = 0;
		try {
			ExifInterface exifInterface = new ExifInterface(path);
			int orientation = exifInterface.getAttributeInt(
					ExifInterface.TAG_ORIENTATION,
					ExifInterface.ORIENTATION_NORMAL);
			switch (orientation) {
			case ExifInterface.ORIENTATION_ROTATE_90:
				degree = 90;
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				degree = 180;
				break;
			case ExifInterface.ORIENTATION_ROTATE_270:
				degree = 270;
				break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return degree;
	}

	public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
		// 旋转图片 动作
		Matrix matrix = new Matrix();
		;
		matrix.postRotate(angle);
		System.out.println("angle2=" + angle);
		// 创建新的图片
		Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
				bitmap.getWidth(), bitmap.getHeight(), matrix, true);
		return resizedBitmap;
	}

	public static Bitmap getImageThumbnail(String imagePath) {
		int width = 1280;
		int height = 1280;

		Bitmap bitmap = null;
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inPreferredConfig = Bitmap.Config.ARGB_4444;
		options.inPurgeable = true;
		options.inInputShareable = true;
		options.inJustDecodeBounds = true;
		// 获取这个图片的宽和高，注意此处的bitmap为null
		bitmap = BitmapFactory.decodeFile(imagePath, options);
		options.inJustDecodeBounds = false; // 设为 false
		// 计算缩放比
		int h = options.outHeight;
		int w = options.outWidth;
		int beWidth = w / width;
		int beHeight = h / height;
		int be = 1;
		if (beWidth < beHeight) {
			be = beWidth;
		} else {
			be = beHeight;
		}
		if (be <= 0) {
			be = 1;
		}
		options.inSampleSize = be;
		// 重新读入图片，读取缩放后的bitmap，注意这次要把options.inJustDecodeBounds 设为 false
		bitmap = BitmapFactory.decodeFile(imagePath, options);
		// 利用ThumbnailUtils来创建缩略图，这里要指定要缩放哪个Bitmap对象

		h = bitmap.getHeight();
		w = bitmap.getWidth();

		if (h < 1280 && w < 1280)
			return bitmap;
		if (w > 1280) {
			height = 1280 * h / w;
			width = 1280;
		} else {
			width = 1280 * w / h;
			height = 1280;
		}

		bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
				ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
		int angle = readPictureDegree(imagePath);
		if (angle != 0) {
			bitmap = rotaingImageView(angle, bitmap);
		}
		return bitmap;
	}

	public static String readFromFile(Context context) {
		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			String foldername = Environment.getExternalStorageDirectory()
					.getPath() + "/data";
			File folder = new File(foldername);

			if (folder == null || !folder.exists()) {
				folder.mkdir();
			}

			String fileName = "/syslz" + ".ini";
			File targetFile = new File(foldername + fileName);
			String readedStr = "";

			try {
				if (!targetFile.exists()) {
					targetFile.createNewFile();
					return "error";
				} else {
					InputStream in = new BufferedInputStream(
							new FileInputStream(targetFile));
					BufferedReader br = new BufferedReader(
							new InputStreamReader(in, "UTF-8"));
					String tmp;

					while ((tmp = br.readLine()) != null) {
						readedStr += tmp;
					}
					br.close();
					in.close();

					return readedStr;
				}
			} catch (Exception e) {
				return e.toString();
			}
		} else {
			return "error";
		}
	}

	public static String SavedToText(Context context, String stringToWrite) {
		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			String foldername = Environment.getExternalStorageDirectory()
					.getPath() + "/data";
			File folder = new File(foldername);

			if (folder == null || !folder.exists()) {
				folder.mkdir();
			}

			String fileName = "/syslz" + ".ini";
			File targetFile = new File(foldername + fileName);
			OutputStreamWriter osw;

			try {
				if (!targetFile.exists()) {
					targetFile.createNewFile();
					osw = new OutputStreamWriter(new FileOutputStream(
							targetFile), "utf-8");
					osw.write(stringToWrite);
					osw.close();
				} else {
					osw = new OutputStreamWriter(new FileOutputStream(
							targetFile, false), "utf-8");
					osw.write(stringToWrite);
					osw.flush();
					osw.close();
				}
			} catch (Exception e) {
			}
		} else {
			return "error";
		}

		return "";
	}

	public static String ConverToString(Date date, String format) {
		DateFormat df = new SimpleDateFormat(format);
		return df.format(date);
	}

	public static Date ConverToDate(String strDate, String format) {
		DateFormat df = new SimpleDateFormat(format);
		try {
			return df.parse(strDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return new Date();
	}

	static public String formatDate(String str, String format) {
		Date date = ConverToDate(str, format);
		return ConverToString(date, format);
	}

	public static Bitmap small(Bitmap bitmap, int angle) {
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();

		float scale = 0;
		if (width > 600)
			scale = (float) (600.0 / width);
		else if (height > 800)
			scale = (float) (800.0 / height);
		else
			return bitmap;

		Matrix matrix = new Matrix();
		matrix.postScale(scale, scale); // 长和宽放大缩小的比例
		if (angle > 0)
			matrix.setRotate(angle);
		Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
				bitmap.getHeight(), matrix, true);
		return resizeBmp;
	}
	
	public static Bitmap scalePic(Bitmap bitmap,int newWidth,int newHeight)
	{
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);
		// create the new Bitmap object
		Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width,
				height, matrix, true);
		return resizedBitmap;
	}
}
